//
// Created by lz on 2/27/21.
//

#ifndef MYWEBLIB_NET_TIMER_H
#define MYWEBLIB_NET_TIMER_H

#include "base/Atomic.h"
#include "base/Timestamp.h"
#include "net/Callbacks.h"

namespace lzweb
{
namespace net
{

///
/// Internal class for timer event.
///

class Timer: noncopyable
{
public:
	Timer(TimerCallback cb, TimeStamp when, double interval)
		: callback_(std::move(cb)),
		  expiration_(when),
		  interval_(interval),
		  repeat_(interval > 0.0),
		  sequence_(s_numCreated_.incrementAndGet())
	{}

	void run() const
	{
		callback_();
	}
	TimeStamp expiration() const
	{ return expiration_; }

	bool repeat() const
	{ return repeat_; }

	int64_t sequence() const
	{ return sequence_; }

	void restart(TimeStamp now);

	static int64_t numCreated() { return s_numCreated_.get(); }


private:
	const TimerCallback callback_;
	TimeStamp expiration_;
	const double interval_;   // interval -> 间隔 ，标志该timer是否repeat
	const bool repeat_;
	const int64_t sequence_;  // 标记创建的第几个timer（根据s_numCreated_）

	static AtomicInt64 s_numCreated_;
};

} //namespace net
}//namespace lzweb

#endif //MYWEBLIB_NET_TIMER_H
